using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;

using GonzalesCore.CoreElements;
using GonzalesCore.CoreManagers;
using Kypris2.CoreElements;
using Kypris2.Utils;
using Jamila2.Tools;

public partial class GonzalesAdminEASDetail : System.Web.UI.Page
{
    #region Variables

    protected PrivateLoginSession CurrentPrivateSession = null;
    protected LogManager CurLogManager = null;
    protected DataObj CurPageDataObj = new DataObj();

    #region ClaimantID
    protected string ClaimantID
    {
        get
        {
            return ViewState["ClaimantID"].ToString();
        }

        set
        {
            ViewState["ClaimantID"] = value;
        }
    }
    #endregion

    #region ResultTable
    protected DataTable ResultTable
    {
        get
        {
            return (DataTable)ViewState["ResultTable"];
        }

        set
        {
            ViewState["ResultTable"] = value;
        }
    }
    #endregion

    #region CompanyID
    protected string CompanyID
    {
        get
        {
            return ViewState["CompanyID"].ToString();
        }

        set
        {
            ViewState["CompanyID"] = value;
        }
    }
    #endregion

    #region EntityID
    protected string EntityID
    {
        get
        {
            return ViewState["EntityID"].ToString();
        }

        set
        {
            ViewState["EntityID"] = value;
        }
    }
    #endregion

    #region GridViewHeader
    protected ArrayList GridViewHeader
    {
        get
        {
            return (ArrayList)ViewState["GridViewHeader"];
        }

        set
        {
            ViewState["GridViewHeader"] = value;
        }
    }
    #endregion

    #region LoadDataErrorMessage
    protected string LoadDataErrorMessage
    {
        get
        {
            return ViewState["LoadDataErrorMessage"].ToString();
        }

        set
        {
            ViewState["LoadDataErrorMessage"] = value;
        }
    }
    #endregion

    #region UnExpectedErrorMessage1
    protected string UnExpectedErrorMessage1
    {
        get
        {
            return ViewState["UnExpectedErrorMessage1"].ToString();
        }

        set
        {
            ViewState["UnExpectedErrorMessage1"] = value;
        }
    }
    #endregion

    #region UnExpectedErrorMessage2
    protected string UnExpectedErrorMessage2
    {
        get
        {
            return ViewState["UnExpectedErrorMessage2"].ToString();
        }

        set
        {
            ViewState["UnExpectedErrorMessage2"] = value;
        }
    }
    #endregion

    #region ApproverReminder
    protected string ApproverReminder
    {
        get
        {
            return ViewState["ApproverReminder"].ToString();
        }

        set
        {
            ViewState["ApproverReminder"] = value;
        }
    }
    #endregion

    #region LevelReminder
    protected string LevelReminder
    {
        get
        {
            return ViewState["LevelReminder"].ToString();
        }

        set
        {
            ViewState["LevelReminder"] = value;
        }
    }
    #endregion

    #region DuplicateExpenseDetailAppr
    protected string DuplicateExpenseDetailAppr
    {
        get
        {
            return ViewState["DuplicateExpenseDetailAppr"].ToString();
        }

        set
        {
            ViewState["DuplicateExpenseDetailAppr"] = value;
        }
    }
    #endregion

    #region DuplicateExpenseDetailLevel
    protected string DuplicateExpenseDetailLevel
    {
        get
        {
            return ViewState["DuplicateExpenseDetailLevel"].ToString();
        }

        set
        {
            ViewState["DuplicateExpenseDetailLevel"] = value;
        }
    }
    #endregion

    #region DeletionFailedMessage
    protected string DeletionFailedMessage
    {
        get
        {
            return ViewState["DeletionFailedMessage"].ToString();
        }

        set
        {
            ViewState["DeletionFailedMessage"] = value;
        }
    }
    #endregion

    #region FolloActualPathMessage
    protected string FolloActualPathMessage
    {
        get
        {
            return ViewState["FolloActualPathMessage"].ToString();
        }

        set
        {
            ViewState["FolloActualPathMessage"] = value;
        }
    }
    #endregion

    #region SavedSuccessMessage
    protected string SavedSuccessMessage
    {
        get
        {
            return ViewState["SavedSuccessMessage"].ToString();
        }

        set
        {
            ViewState["SavedSuccessMessage"] = value;
        }
    }
    #endregion

    #region SavedFailedMessage
    protected string SavedFailedMessage
    {
        get
        {
            return ViewState["SavedFailedMessage"].ToString();
        }

        set
        {
            ViewState["SavedFailedMessage"] = value;
        }
    }
    #endregion

    #endregion

    #region Events
    protected void Page_Load(object sender, EventArgs e)
    {
        this.SessionCheck();

        // check if any deletion occur
        this.DataDelete();
        

        if (!IsPostBack)
        {
            if (this.CurrentPrivateSession.CurrentLoggedOnUser.IsFinanceAdmin)
                if (!this.CurrentPrivateSession.CurrentLoggedOnUser.IsFinancialManager)
                {
                    Button_Submit.Visible = false;
                }

            if (Request.QueryString["id"] != null && Request.QueryString["id"].Length == 36)
            {
                this.ClaimantID = Request.QueryString["id"];

                this.PageComponentSetup();
                this.SwitchLanguage();

                this.LoadData();
                if (this.ResultTable != null)
                {
                    this.BindData(new DataView(this.ResultTable));
                }

                // log down the history
                this.CurLogManager.LogMessage("[GonzalesAdminEASDetail] : Exception Approver for Claimant(" + this.ClaimantID + ", " + this.LabelValue_Personnel.Text + ") viewed", this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.User);

            }
            else
            {                
                this.ShowErrorMessage(this.FolloActualPathMessage);
                Response.End();
            }
        }
        //added by mei chze on 13072012
        this.DataEdit();
    }

    protected void ImageButton_Cancel_Click(object sender, ImageClickEventArgs e)
    {
        Response.Redirect("GonzalesAdminEASLListing.aspx?entity=" + this.EntityID + "&company=" + this.CompanyID);
    }

    protected void Button_Submit_Click(object sender, EventArgs e)
    {
        //string lsQueryString = Request.QueryString["did"];

        if (this.DataValidate())
        {
            using (UserManager CurUserManager = new UserManager(this.CurrentPrivateSession))
            {
                if (Button_Submit.Text.Equals("Add"))
                {
                    if (!CurUserManager.AddExceptionalApprover(
                    this.ClaimantID,
                    this.HiddenField_PersonnelInternalID.Value,
                    Int32.Parse(this.TextBox_Level.Text)))
                    {

                        this.ShowErrorMessage(this.SavedFailedMessage);
                        this.CurLogManager.LogError("[GonzalesAdminEASDetail.Button_Submit_Click] : Failed at CurUserManager.AddExceptionalApprover() : " + CurUserManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                    }
                    else
                    {

                        this.ShowMessage(this.SavedSuccessMessage);
                        
                        this.LoadData();
                        Button_Submit.Text = "Add";
                        TextBox_Level.Enabled = true;
                        LabelValue_Approver.Text = "";
                        if (this.ResultTable != null)
                        {
                            this.BindData(new DataView(this.ResultTable));
                        }
                        SystemUser App = null;
                        using (UserManager userManager = new UserManager(this.CurrentPrivateSession))
                        {
                            //App = userManager.GetUserByInternalID(Request.QueryString["did"]);
                            App = userManager.GetUserByInternalID(this.HiddenField_PersonnelInternalID.Value); // Thang Nguyen Edited 08/03/2013

                            // log down the history
                           // this.CurLogManager.LogMessage("[GonzalesAdminEASDetail.Button_Submit_Click] : New Exception Approver (" + this.HiddenField_PersonnelInternalID.Value + ", " + this.LabelValue_Approver.Text + ") added, to Claimant(" + this.ClaimantID + ", " + this.LabelValue_Personnel.Text + ")", this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.User);
                            //FRANK update jan-2013
                            if (App != null) // ThangNguyen added this line: 08/03/2013
                            {
                                this.CurLogManager.LogMessageFull("[GonzalesAdminEASDetail.Button_Submit_Click] : New Exception Approver (" + this.HiddenField_PersonnelInternalID.Value + ", " + this.LabelValue_Approver.Text + ") added, to Claimant(" + this.ClaimantID + ", " + this.LabelValue_Personnel.Text + ")", this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.User //keep old things
                                    , this.ClaimantID,
                                    this.ClaimantID,
                                    "", "Add",
                                    this.HiddenField_PersonnelInternalID.Value
                                    , "", "", "", App.ApprovingLimit.ToString(), "", "", "", "", "", "", double.Parse(App.ApprovingLimit.ToString()), double.Parse(App.ApprovingLimit.ToString()), "GonzalesAdminEASDetail", this.TextBox_Level.Text);
                            }
                         }
                    }
                }
                else
                {
                    if (!CurUserManager.EditExceptionalApprover(
                    this.ClaimantID, Request.QueryString["did"],
                    this.HiddenField_PersonnelInternalID.Value))
                    {

                        this.ShowErrorMessage(this.SavedFailedMessage);
                        this.CurLogManager.LogError("[GonzalesAdminEASDetail.Button_Submit_Click] : Failed at CurUserManager.EditExceptionalApprover() : " + CurUserManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                    }
                    else
                    {
                        // log down the history
                        SystemUser claimant = null;
                        SystemUser App = null;
                        SystemUser NApp = null;
                        using (UserManager userManager = new UserManager(this.CurrentPrivateSession))
                        {
                            claimant = userManager.GetUserByInternalID(ClaimantID);
                            App = userManager.GetUserByInternalID(Request.QueryString["did"]);
                            NApp = userManager.GetUserByInternalID(this.HiddenField_PersonnelInternalID.Value);
                        }
                        //FRANK jan-2013
                        //this.CurLogManager.LogMessage("[GonzalesAdminApproverReplacmen.Button_Submit_Click] : Edit Exception Approver ("
                        //+ App.InternalID + ", " + App.DisplayName
                        //+ ",[old approver] to " + NApp.InternalID + ", " + NApp.DisplayName + " ,[new approver]) updated, to Claimant("
                        //+ claimant.InternalID + ", " + claimant.DisplayName + ")", this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.User);

                        this.CurLogManager.LogMessageFull("[GonzalesAdminApproverReplacmen.Button_Submit_Click] : Edit Exception Approver ("
                        + App.InternalID + ", " + App.DisplayName
                        + ",[old approver] to " + NApp.InternalID + ", " + NApp.DisplayName + " ,[new approver]) updated, to Claimant("
                        + claimant.InternalID + ", " + claimant.DisplayName + ")", this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.User //keep old things
                        , this.ClaimantID,
                        this.ClaimantID,
                        "","Update",
                        NApp.InternalID
                        , "", "", "", "", "", "", "", "", "", "", double.Parse(NApp.ApprovingLimit.ToString()), double.Parse(NApp.ApprovingLimit.ToString()), "GonzalesAdminEASDetail", this.TextBox_Level.Text);

                        #region //change claim next approver to current approver
                        using (ClaimManager CurClaimManager = new ClaimManager(this.CurrentPrivateSession))
                        {
                            DataTable ResultClaim = CurClaimManager.GetClaimHeaderByClaimByAndClaimApprover(this.ClaimantID, HiddenField_StoreNextApproverID.Value);

                            if (ResultClaim != null)
                            {
                                foreach (DataRow ResultRow in ResultClaim.Rows)
                                {
                                    string ClaimID = ResultRow["internal_id"].ToString();
                                    SystemUser Approver = null;
                                    SystemUser NewApp = null;
                                    using (UserManager userManager = new UserManager(this.CurrentPrivateSession))
                                    {
                                        Approver = userManager.GetUserByInternalID(ResultRow["claim_next_approver"].ToString());
                                        NewApp = userManager.GetUserByInternalID(this.HiddenField_PersonnelInternalID.Value);
                                    }
                                    if (!CurClaimManager.UpdateClaimHeaderWhenChangeApprover(ClaimID, this.HiddenField_PersonnelInternalID.Value))
                                    {
                                        this.ShowErrorMessage(this.SavedFailedMessage);
                                        this.CurLogManager.LogError("[GonzalesAdminEASDetail.Button_Submit_Click] : Failed at CurClaimManager.UpdateClaimHeaderWhenChangeApprover() : " + CurUserManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                                    }
                                    else
                                    {
                                        //log the action
                                        //FRANK jan-2013
                                       // this.CurLogManager.LogMessage("[GonzalesAdminEASDetail.Button_Submit_Click] : [GonzalesAdminApproverExceptionChange] :Claim ID:'" + ResultRow["Claim_id"].ToString() + "' exception approver from(" + Approver.InternalID + ", " + Approver.DisplayName + "), to (" + NewApp.InternalID + ", " + NewApp.DisplayName + ")changed)", this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.User);
                                        this.CurLogManager.LogMessageFull("[GonzalesAdminEASDetail.Button_Submit_Click] : [GonzalesAdminApproverExceptionChange] :Claim ID:'" + ResultRow["Claim_id"].ToString() + "' exception approver from(" + Approver.InternalID + ", " + Approver.DisplayName + "), to (" + NewApp.InternalID + ", " + NewApp.DisplayName + ")changed)", this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.User
                                        , ResultRow["Claim_id"].ToString(),
                                        ResultRow["Claim_id"].ToString(),
                                        "", "Update",
                                        NewApp.InternalID
                                        , "", "", "", "", "", "", "", "", "", "", double.Parse(NewApp.ApprovingLimit.ToString()), double.Parse(NewApp.ApprovingLimit.ToString()), "GonzalesAdminEASDetail", "0");
                                    }
                                }
                            }
                        #endregion
                       
                            #region AfterChangeAllPendingAprrovedClaim
                            this.ShowMessage(this.SavedSuccessMessage);
                            this.LoadData();
                            Button_Submit.Text = "Add";
                            TextBox_Level.Enabled = true;
                            LabelValue_Approver.Text = "";
                            if (this.ResultTable != null)
                            {
                                this.BindData(new DataView(this.ResultTable));
                            }
                            this.ClientScript.RegisterStartupScript(this.GetType(), "Data Saved", "<script language=\"javaScript\">" +
                            "alert('" + this.SavedSuccessMessage + "');" + "window.location.href='#';" + "<" + "/script>");
                            Response.Redirect("GonzalesAdminEASDetail.aspx?id=" + this.ClaimantID);
                            #endregion

                        }
                    }
                }             
            }
        }
    }

    #region OnRowCreated
    protected void OnRowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            TableCellCollection cells = e.Row.Cells;

            for (int i = 0; i < this.GridViewHeader.Count; i++)
            {
                cells[i].Text = this.GridViewHeader[i].ToString();
            }
        }
    }
    #endregion


    # region Change all unapprove claim to new approver.

    #endregion

    #endregion

    #region Customized Methods

    #region SessionCheck
    public void SessionCheck()
    {

        if (Session[GonzalesCommonNamingConvention.CurrentPrivateSession] != null)
        {
            this.CurrentPrivateSession = (PrivateLoginSession)Session[GonzalesCommonNamingConvention.CurrentPrivateSession];
            this.CurLogManager = new LogManager(this.CurrentPrivateSession);    // activate Log Manager
        }
        else
        {
            Response.Redirect(GonzalesErrorPageRedirect.SessionError);
        }

    }
    #endregion

    #region PageComponentSetup
    protected void PageComponentSetup()
    {
        using (UserManager CurUserManager = new UserManager(this.CurrentPrivateSession))
        {
            SystemUser CurUser = CurUserManager.GetUserByInternalID(this.ClaimantID);
            if (CurUser != null)
            {
                this.LabelValue_Personnel.Text = CurUser.DisplayName;
            }
            else
            {
                this.CurLogManager.LogError("[GonzalesAdminEASDetail.PageComponentSetup] : Failed at CurUserManager.GetUserByInternalID('" + this.ClaimantID + "') : " + CurUserManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                this.ShowErrorMessage(this.LoadDataErrorMessage);
            }
        }

        // cancel button
        this.ImageButton_Cancel.Attributes["onclick"] = "return confirm('All unsaved data will be lost, are you sure?');";
        if (Request.QueryString["EDIT"] != null && Request.QueryString["EDIT"].CompareTo("TRUE") == 0)
        {
        this.Button_Submit.Attributes["onclick"] = "return confirm('All pending claim will submit to this approver, are you sure change to this approver?');";   
        }
        // browse button
        this.Button_Browse.Attributes["onclick"] = "ShowModal('AddressBook', document.getElementById('ModalResult')); return false;";
    }
    #endregion

    #region SwitchLanguage
    protected void SwitchLanguage()
    {
        try
        {
            using (MultiLingualFactory CurLanguageFactory = MultiLingualEngine.GetMultiLingualFactory(this, this.CurrentPrivateSession.CurrentLoggedOnUser.PreferedLanguage.InternalID))
            {
                this.Label_AddNew.Text = CurLanguageFactory.DisplayValue("AddNew");
                this.Label_Approver.Text = CurLanguageFactory.DisplayValue("Approver");
                this.Label_AuthorizedLimit2.Text = CurLanguageFactory.DisplayValue("AuthorizedLimit2");
                this.Label_Claimant.Text = CurLanguageFactory.DisplayValue("Claimant");
                this.Label_Information.Text = CurLanguageFactory.DisplayValue("Information");
                this.Label_PageTitle.Text = CurLanguageFactory.DisplayValue("PageTitle");
                this.Button_Browse.Text = CurLanguageFactory.DisplayValue("Browse");
                this.Button_Submit.Text = CurLanguageFactory.DisplayValue("Submit");

                this.GridViewHeader = new ArrayList();
                this.GridViewHeader.Add(CurLanguageFactory.DisplayValue("Level"));
                this.GridViewHeader.Add(CurLanguageFactory.DisplayValue("EmployeeID"));
                this.GridViewHeader.Add(CurLanguageFactory.DisplayValue("ActiveDirectoryName"));
                this.GridViewHeader.Add(CurLanguageFactory.DisplayValue("DisplayName"));
                this.GridViewHeader.Add(CurLanguageFactory.DisplayValue("ApprovingLimit"));

                this.LoadDataErrorMessage = CurLanguageFactory.DisplayValue("LoadDataErrorMessage");
                this.UnExpectedErrorMessage1 = CurLanguageFactory.DisplayValue("UnExpectedErrorMessage1");
                this.UnExpectedErrorMessage2 = CurLanguageFactory.DisplayValue("UnExpectedErrorMessage2");
                this.ApproverReminder = CurLanguageFactory.DisplayValue("ApproverReminder");
                this.LevelReminder = CurLanguageFactory.DisplayValue("LevelReminder");
                this.DuplicateExpenseDetailAppr = CurLanguageFactory.DisplayValue("DuplicateExpenseDetailAppr");
                this.DuplicateExpenseDetailLevel = CurLanguageFactory.DisplayValue("DuplicateExpenseDetailLevel");
                this.DeletionFailedMessage = CurLanguageFactory.DisplayValue("DeletionFailedMessage");
                this.FolloActualPathMessage = CurLanguageFactory.DisplayValue("FolloActualPathMessage");
                this.SavedSuccessMessage = CurLanguageFactory.DisplayValue("SavedSuccessMessage");
                this.SavedFailedMessage = CurLanguageFactory.DisplayValue("SavedFailedMessage");

            }
        }
        catch (Exception ex)
        {
            this.CurLogManager.LogError("[GonzalesAdminClaimantsDetail.SwitchLanguage.EX] : " + ex.Message, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.User);
        }

    }
    #endregion

    #region ShowErrorMessage
    protected void ShowErrorMessage(string ErrorMessage)
    {
        this.Table_MessageBox.Visible = true;
        this.Table_MessageBox.Rows[0].Cells[0].Text = ErrorMessage;
        this.Table_MessageBox.Rows[0].Cells[0].CssClass = "ErrorBox";
    }
    #endregion

    #region ShowMessage
    protected void ShowMessage(string Message)
    {
        this.Table_MessageBox.Visible = true;
        this.Table_MessageBox.Rows[0].Cells[0].Text = Message;
        this.Table_MessageBox.Rows[0].Cells[0].CssClass = "MessageBox";
    }
    #endregion

    #endregion

    #region Data Operation

    #region LoadData
    protected void LoadData()
    {
        if (this.ClaimantID != null)
        {
            using (UserManager CurUserManager = new UserManager(this.CurrentPrivateSession))
            {
                SystemUser CurUser = CurUserManager.GetUserByInternalID(this.ClaimantID);
                if (CurUser != null)
                {
                    this.CompanyID = CurUser.FromCompany.InternalID;
                    this.EntityID = CurUser.FromCompany.Entity.InternalID;
                }
                else
                {
                    string LogID = SwissArmy.UniqueID();
                    this.CurLogManager.LogError(LogID, "[] : Failed at CurUserManager.GetUserByInternalID('" + this.ClaimantID + "') : " + CurUserManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                    this.ShowErrorMessage(this.UnExpectedErrorMessage1 + LogID + this.UnExpectedErrorMessage2);
                }

                SystemUsers ApproversList = CurUserManager.GetExceptionalApproversMatrix(this.ClaimantID);

                if (ApproversList != null)
                {

                    this.ResultTable = new DataTable();
                    
                    this.ResultTable.Columns.Add(new DataColumn(this.CurPageDataObj.InternalID, Type.GetType("System.String")));
                    this.ResultTable.Columns.Add(new DataColumn(this.CurPageDataObj.Level, Type.GetType("System.Int32")));
                    this.ResultTable.Columns.Add(new DataColumn(this.CurPageDataObj.EmployeeID, Type.GetType("System.String")));
                    this.ResultTable.Columns.Add(new DataColumn(this.CurPageDataObj.DisplayName, Type.GetType("System.String")));
                    this.ResultTable.Columns.Add(new DataColumn(this.CurPageDataObj.ActiveDirectoryName, Type.GetType("System.String")));
                    this.ResultTable.Columns.Add(new DataColumn(this.CurPageDataObj.DeleteLink, Type.GetType("System.String")));
                    this.ResultTable.Columns.Add(new DataColumn(this.CurPageDataObj.ApprovingLimit, Type.GetType("System.String")));
                    //added by mei chze on 13072012
                    this.ResultTable.Columns.Add(new DataColumn(this.CurPageDataObj.EditLink, Type.GetType("System.String")));

                    for (int x = 0; x < ApproversList.Count; x++)
                    {
                        DataRow ResultRow = this.ResultTable.NewRow();                        

                        ResultRow[this.CurPageDataObj.InternalID] = ApproversList[x].InternalID;
                        ResultRow[this.CurPageDataObj.Level] = ApproversList[x].ApproverLevel;
                        ResultRow[this.CurPageDataObj.EmployeeID] = ApproversList[x].EmployeeID;
                        ResultRow[this.CurPageDataObj.DisplayName] = ApproversList[x].DisplayName;
                        ResultRow[this.CurPageDataObj.ActiveDirectoryName] = ApproversList[x].EmailID;
                        if(ApproversList[x].ApprovingCurrency != null)
                            ResultRow[this.CurPageDataObj.ApprovingLimit] = ApproversList[x].ApprovingCurrency.DisplayName.ToString() + " " + ApproversList[x].ApprovingLimit.ToString();
                        if (this.CurrentPrivateSession.CurrentLoggedOnUser.IsFinanceAdmin)
                        {
                            if (this.CurrentPrivateSession.CurrentLoggedOnUser.IsFinancialManager)
                            {
                                ResultRow[this.CurPageDataObj.DeleteLink] = "<a class='GridViewLink' href='GonzalesAdminEASDetail.aspx?DELETE=TRUE&id=" + this.ClaimantID + "&did=" + ApproversList[x].InternalID + "' onclick=\"return confirm('This action will not able to be undone, continue?');\">Delete</a>";
                                ResultRow[this.CurPageDataObj.EditLink] = "<a class='GridViewLink' href='GonzalesAdminEASDetail.aspx?EDIT=TRUE&id=" + this.ClaimantID + "&did=" + ApproversList[x].InternalID + "'>Edit</a>";
                            }
                        }
                        else
                        {
                            ResultRow[this.CurPageDataObj.DeleteLink] = "<a class='GridViewLink' href='GonzalesAdminEASDetail.aspx?DELETE=TRUE&id=" + this.ClaimantID + "&did=" + ApproversList[x].InternalID + "' onclick=\"return confirm('This action will not able to be undone, continue?');\">Delete</a>";
                            ResultRow[this.CurPageDataObj.EditLink] = "<a class='GridViewLink' href='GonzalesAdminEASDetail.aspx?EDIT=TRUE&id=" + this.ClaimantID + "&did=" + ApproversList[x].InternalID + "'>Edit</a>";
                        }
                        this.ResultTable.Rows.Add(ResultRow);
                    }
                }
                else
                {
                    this.CurLogManager.LogError("[GonzalesAdminEASDetail.LoadData] : Failed at : " + CurUserManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                }
            }
        }
    }
    #endregion

    #region DataValidate
    protected bool DataValidate()
    {
        bool valid = true;
        StringBuilder ErrorMessages = new StringBuilder("<ul>");

        if (this.HiddenField_PersonnelInternalID.Value.Length == 0)
        {
            valid = false;
            ErrorMessages.AppendLine("<li>" + this.ApproverReminder + "</li>");
        }

        int tmp = 0;
        if (!Int32.TryParse(this.TextBox_Level.Text, out tmp) || tmp < 0)
        {
            valid = false;
            ErrorMessages.AppendLine("<li>" + this.LevelReminder + "</li>");
        }

        // check if having duplicate entry
        if (valid && this.ResultTable != null)
        {
            foreach (DataRow ResultRow in this.ResultTable.Rows)
            {
                if (ResultRow[this.CurPageDataObj.InternalID].ToString().CompareTo(this.HiddenField_PersonnelInternalID.Value) == 0)
                {
                    valid = false;
                    ErrorMessages.AppendLine("<li>" + this.DuplicateExpenseDetailAppr + "</li>");
                    break;
                }
                if(Button_Submit.Text.ToUpper().Equals("ADD"))
                {
                        if (Convert.ToInt32(ResultRow[this.CurPageDataObj.Level]) == Int32.Parse(this.TextBox_Level.Text))
                          {
                               valid = false;
                               ErrorMessages.AppendLine("<li>" + this.DuplicateExpenseDetailLevel + "</li>");
                               break;
                          }
                }               
            }
        }

        ErrorMessages.AppendLine("</ul>");

        if (!valid) this.ShowErrorMessage(ErrorMessages.ToString());

        return valid;
    }
    #endregion

    #region DataDelete
    protected void DataDelete()
    {
        bool smooth = true;

        if (Request.QueryString["id"] != null && Request.QueryString["id"].Length == 36 &&
            Request.QueryString["DELETE"] != null && Request.QueryString["DELETE"].CompareTo("TRUE") == 0 &&
            Request.QueryString["did"] != null && Request.QueryString["did"].Length == 36)
        {
            this.ClaimantID = Request.QueryString["id"];

            //update by mei chze on 28/08/2012
         
               #region check if have pending claim 
            using (ClaimManager CurClaimManager = new ClaimManager(this.CurrentPrivateSession))
            {
                DataTable ResultClaim = CurClaimManager.GetClaimHeaderByClaimByAndClaimApprover(this.ClaimantID, Request.QueryString["did"]);

                if (ResultClaim != null)
                {
                    int count = ResultClaim.Rows.Count;
                    if (count > 0)
                    {
                         SystemUser NewApp = null;
                         using (UserManager userManager = new UserManager(this.CurrentPrivateSession))
                         {
                             NewApp = userManager.GetUserByInternalID(Request.QueryString["did"]);
                         }
                        smooth = false;
                        string errMessage ="Error. Having pending approver claim for approver " + NewApp.DisplayName + ". Solution: Please choose EDIT function to change another approver." ;
                        this.ClientScript.RegisterStartupScript(this.GetType(), "Data Saved", "<script language=\"javaScript\">" +
                           "alert('" + errMessage + "');" + "window.location.href='#';" + "<" + "/script>");
                       // Response.Redirect("GonzalesAdminEASDetail.aspx?id=" + this.ClaimantID);
                    }
                }
            }
                        #endregion

            if (smooth)
            {
                using (UserManager CurUserManager = new UserManager(this.CurrentPrivateSession))
                {
                    smooth = CurUserManager.DeleteExceptionalApprover(this.ClaimantID, Request.QueryString["did"]);

                    if (!smooth)
                    {
                        this.CurLogManager.LogError("[GonzalesAdminEASDetail.DataDelete] : Failed at CurUserManager.DeleteExceptionalApprover('" + this.ClaimantID + "', Request.QueryString['" + Request.QueryString["did"] + "']) : ", this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                        this.ShowErrorMessage(this.DeletionFailedMessage);
                    }
                    else
                    {
                        //FRANK update jan-2013
                        this.CurLogManager.LogMessageFull("[GonzalesAdminEASDetail.DataDelete] : Deleted ('" + this.ClaimantID + "', Request.QueryString['" + Request.QueryString["did"] + "']) : ", this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.User //keep old things
                            , this.ClaimantID,
                            this.ClaimantID,
                            "", "Delete",
                            Request.QueryString["did"]
                            , "", "", "", "", "", "", "", "", "", "", 0, 0, "GonzalesAdminEASDetail", this.TextBox_Level.Text);
                    }
                }
            }
            if (smooth)
            {
                Response.Redirect("GonzalesAdminEASDetail.aspx?id=" + this.ClaimantID);
            }
        }
    }

    #endregion


    //added by mei chze on 13072012
    #region DataEdit
    protected void DataEdit()
    {
        bool smooth = true;
        DataTable  ResultRow = null;

        if (Request.QueryString["id"] != null && Request.QueryString["id"].Length == 36 &&
            Request.QueryString["EDIT"] != null && Request.QueryString["EDIT"].CompareTo("TRUE") == 0 &&
            Request.QueryString["did"] != null && Request.QueryString["did"].Length == 36)
        {
           Button_Submit.Text = "Edit";
           TextBox_Level.Enabled = false;
            this.ClaimantID = Request.QueryString["id"];

            using (UserManager CurUserManager = new UserManager(this.CurrentPrivateSession))
            {
                ResultRow = CurUserManager.GetDetailNextApproverForException(this.ClaimantID, Request.QueryString["did"]);

                if (!smooth)
                {
                    this.CurLogManager.LogError("[GonzalesAdminEASDetail.DataEdit] : Failed at CurUserManager.GetDetailNextApproverForException('" + this.ClaimantID + "', Request.QueryString['" + Request.QueryString["did"] + "']) : ", this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                    this.ShowErrorMessage(this.DeletionFailedMessage);
                }
           

                if (smooth)
                {

                    SystemUser sy = CurUserManager.GetUserByInternalID(ResultRow.Rows[0]["approver_id"].ToString());
                   // LabelValue_Approver.Text =sy.DisplayName ;
                   // HiddenField_PersonnelInternalID.Value = sy.InternalID;
                    HiddenField_StoreNextApproverID.Value = sy.InternalID;
                    TextBox_Level.Text = ResultRow.Rows[0]["approving_level"].ToString();
                }
            }
        }
    }

    #endregion
    private void BindData(DataView result)
    {
        this.GridViewResult.DataSource = result;
        this.GridViewResult.DataBind();
    }

    private void BindData(DataView result, int pageindex)
    {
        this.GridViewResult.PageIndex = pageindex;
        this.GridViewResult.DataSource = result;
        this.GridViewResult.DataBind();
    }

    #endregion

    #region Class: DataObj

    protected class DataObj
    {
        public readonly string InternalID = "InternalID";
        public readonly string Level = "Level";
        public readonly string EmployeeID = "EmployeeID";
        public readonly string ActiveDirectoryName = "ActiveDirectoryName";
        public readonly string DisplayName = "DisplayName";
        public readonly string ApprovingLimit = "ApprovingLimit";
        public readonly string DeleteLink = "DeleteLink";
        //added by mei chze on 13072012
        public readonly string EditLink = "EditLink";

    }

    #endregion


    protected void Button_Cancel_Click(object sender, EventArgs e)
    {
        Button_Submit.Text = "Add";
        TextBox_Level.Text = "";
        TextBox_Level.Enabled = true;
        LabelValue_Approver.Text = "";
        Response.Redirect("GonzalesAdminEASDetail.aspx?id=" + this.ClaimantID);
    }
}
